import React, { Component } from "react"
import { withRouter } from "react-router"
import echarts from 'echarts/lib/echarts';
import 'echarts/lib/chart/radar';
import 'echarts/lib/component/legend';
import styles from './projectDetail.less'
import Header from '@/components/header'
import { projectDetail, projectName, projectRatio, projectEquipsList, projectOutline } from '@/services'
import Radar from '@/components/radar'
import EditProjectModal from '@/components/editProjectModal'
import md5 from 'js-md5';
import { formatNumber, parseHour } from '@/utils'

function formatNum(num, demical=1){
  let result = num >= 10000 ? `${(num/10000).toFixed(demical)}` : (num*1).toFixed(demical);
  return result ? `${result}`.split('.') : ["0"];
}
class ProjectDetail extends Component {

  constructor(props){
    super(props);
    this.state = {
      statistics: {},
      projectInfo: {},
      projectRadar: [],
      radarData: {},
      projectCars: [],
      expandCar: 0, //展开的车辆
      projectTime: {},
    }
  }

  componentDidMount(){
    this.init()
  }

  init = async () => {
    try {
      const statistics = await projectDetail({ projectId: this.props.location.state.id });
      if(statistics.code===200){
        this.setState({ statistics: statistics.data })
      }
      const projectInfo = await projectName({ projectId: this.props.location.state.id });
      if(projectInfo.code===200){
        this.setState({ projectInfo: projectInfo.data })
      }
      const projectRadar = await projectRatio({ projectId: this.props.location.state.id });
      if(projectRadar.code===200){
        this.setState({ 
          radarData: projectRadar.data,
          projectRadar: [
          {
            name: '公司平均值',
            value: [ 
              projectRadar.data.averageCompanyData.totalQuantityNum,
              projectRadar.data.averageCompanyData.workTime,
              projectRadar.data.averageCompanyData.useRatio,
              projectRadar.data.averageCompanyData.validPumpRatio,
              projectRadar.data.averageCompanyData.totalOilNum,
            ],
            areaStyle: {
              color: '#FB4033',
            },
            itemStyle: {
              color: '#FB4033',
            }
          },
          {
            name: '本工程数据',
            value: [ 
              projectRadar.data.thisProjectData.totalQuantityNum,
              projectRadar.data.thisProjectData.workTime,
              projectRadar.data.thisProjectData.useRatio,
              projectRadar.data.thisProjectData.validPumpRatio,
              projectRadar.data.thisProjectData.totalOilNum,
            ],
            areaStyle: {
              color: '#666666',
            },
            itemStyle: {
              color: '#666666',
            }
          },
          {
            name: '行业平均值',
            value: [ 
              projectRadar.data.averageProfessionData.totalQuantityNum,
              projectRadar.data.averageProfessionData.workTime,
              projectRadar.data.averageProfessionData.useRatio,
              projectRadar.data.averageProfessionData.validPumpRatio,
              projectRadar.data.averageProfessionData.totalOilNum,
            ],
            areaStyle: {
              color: '#D0B17E',
            },
            itemStyle: {
              color: '#D0B17E',
            }
          },
        ]},this.renderRadar)
      }
      const equipList = await projectEquipsList({ projectId: this.props.location.state.id })
      if(equipList.code===200){
        this.setState({ projectCars: equipList.data })
      }
      const projectTime = await projectOutline({ projectId: this.props.location.state.id })
      if(projectTime.code===200){
        this.setState({ projectTime: projectTime.data })
      }
    } catch (error) {
      console.log(error)
    }
  }

  renderRadar = () => {
    const { radarData } = this.state;
    this.radar = echarts.init(document.getElementById('radar'));
    this.radar.setOption({
      tooltip: {
        confine:true,
        formatter: (data)=>{
          return `
          ${data.name}<br />
          泵送方量: ${data.value[0]}方<br />
          工作时间: ${(data.value[1]/3600).toFixed(2)}小时<br />
          设备利用率: ${data.value[2]}%<br />
          有效泵送率: ${data.value[3]}%<br />
          工程油耗: ${data.value[4]}升
          `
        }
      },
      legend: {
        right: 12,
        top: 87,
        data:['公司平均值','本工程数据','行业平均值'],
        orient: 'vertical',
        icon: 'rect'
      },
      grid: {
        top: 0,
        bottom: 0,
        left: 100,
        right: 0,
      },
      radar: {
        name: {
          color: '#000000',
          fontSize: 16,
        },
        indicator: [
          { name: '泵送方量', },
          { name: '工作时间', },
          { name: '设备利用率', },
          { name: '有效泵送率', },
          { name: '工程油耗', },
        ],
        // indicator: [
        //   { name: '泵送方量', max: radarData.averageProfessionData.totalQuantityNum*1.5 },
        //   { name: '工作时间', max: radarData.averageProfessionData.workTime*1.5 },
        //   { name: '设备利用率', max: radarData.averageProfessionData.useRatio*1.5 },
        //   { name: '有效泵送率', max: radarData.averageProfessionData.validPumpRatio*1.5 },
        //   { name: '工程油耗', max: radarData.averageProfessionData.totalOilNum*1.5 },
        // ],
        radius: '52%',
        center: ['50%', '60%']
      },
      series: [{
          name: '工程画像',
          type: 'radar',
          data: this.state.projectRadar
      }]
    })
  }
  
  toCarDetail = (equipCode) => {
    this.props.history.push(`carDetail?equipCode=${equipCode}&source=selfpage&token=${md5(equipCode+'selfpage'+'s$31d0dl1!~93-kHj^S')}`)
  }

  render(){
    const { statistics, projectInfo, projectRadar, projectCars, expandCar, projectTime } = this.state;
    const defaultData = {
      projId: projectInfo.projectId,
      totalOil: statistics.totalOilNum,
      totalDuration: statistics.workDuration,
      totalQuantity: statistics.totalQuantityNum,
      projName: projectInfo.name,
      status: projectInfo.status,
      address: projectInfo.address,
    }
    const totalOilNum = formatNum(statistics.totalOilNum);
    const tempWorkDuration = parseHour(statistics.workDuration);
    const workDuration= formatNum(tempWorkDuration);
    const totalQuantityNum = formatNum(statistics.totalQuantityNum);
    const pumpDuration = parseHour(statistics.pumpDuration);
    const oilPerQuantity = formatNum(statistics.oilPerQuantity,2);
    return (
      <div className={styles.projectDetail}>
        <Header>工程详情</Header>
        <div style={{ backgroundColor: '#FAFAFA' }}>
          <div className={styles.statistics_top}>
            <div className={styles.item}>
            <div className={styles.item_value}>{totalOilNum[0]!=='NaN'?totalOilNum[0]:0}{totalOilNum[1] && '.'}<span className={styles.standard}>{totalOilNum[1]}{statistics.totalOilNum>=10000 && '万'}L</span></div>
              <div className={styles.item_name}>油耗</div>
            </div>
            <div className={styles.item}>
            <div className={styles.item_value}>{workDuration[0]}{workDuration[1] && '.'}<span className={styles.standard}>{workDuration[1]}{tempWorkDuration>=10000 && '万'}H</span></div>
              <div className={styles.item_name}>工作时间</div>
            </div>
            <div className={styles.item}>
            <div className={styles.item_value}>{totalQuantityNum[0]!=='NaN'?totalQuantityNum[0]:0}{totalQuantityNum[1] && '.'}<span className={styles.standard}>{totalQuantityNum[1]}{statistics.totalQuantityNum>=10000 && '万'}M³</span></div>
              <div className={styles.item_name}>泵送总量</div>
            </div>
          </div>
          <img className={styles.inform_solid} src={require('../assets/img/statiscs_solid.png')} />
          <div className={styles.statistics_bottom}>
            <div className={styles.item}>
            <div className={styles.item_value}>{pumpDuration>=10000 ? (pumpDuration/10000).toFixed(1) : pumpDuration}<span className={styles.standard}>{pumpDuration>=10000 && '万'}h</span></div>
              <div className={styles.item_name}>泵送计时</div>
            </div>
            <div className={styles.item} onClick={()=>{ alert('有效泵送率：统计范围内泵送计时/统计范围内开机时间') }}>
              <div className={styles.item_value}>{statistics.validPumpRatio||0}<span className={styles.standard}>%</span></div>
              <div className={styles.item_name}>有效泵送率<img src={require('../assets/img/question.png')} className={styles.icon_question} /></div>
            </div>
            <div className={styles.item} onClick={()=>{ alert('设备利用率：统计范围内有效工作时间（泵送时间+待料时间+转场时间）/统计范围内开机时间') }}>
              <div className={styles.item_value}>{statistics.useRatio||0}<span className={styles.standard}>%</span></div>
              <div className={styles.item_name}>设备利用率<img src={require('../assets/img/question.png')} className={styles.icon_question} /></div>
            </div>
            <div className={styles.item}>
            <div className={styles.item_value}>{oilPerQuantity[0]!=='NaN'?oilPerQuantity[0]:0}{oilPerQuantity[1] && '.'}{oilPerQuantity[1]}<span className={styles.standard}>{statistics.oilPerQuantity>=10000 && '万'}L/方</span></div>
              <div className={styles.item_name}>方量油耗</div>
            </div>
          </div>
          <div className={styles.inform}>
            <div className={styles.inform_top}>
              <div className={styles.inform_name}>
                {projectInfo.name}
                <img className={styles.inform_eidt} onClick={()=>{ this.editModal && this.editModal.show(defaultData) }} src={require('../assets/img/map/edit.png')} />
              </div>
              <div className={styles.inform_status} style={{  backgroundColor: projectInfo.online == 1 ? '#2DD5B8' : 'rgb(152, 152, 152)' }}>{projectInfo.online==1?'进行中':'已完工'}</div>
            </div>
            <div className={styles.inform_address}>
              {projectInfo.address}
            </div>
          </div>
        </div>
        {/* 工程画像 */}
        <div className={styles.radar}>
          <div className={styles.radar_title}>工程画像</div>
          <div id="radar" className={styles.radar_chart}></div>
        </div>
        {/* 参与车辆 */}
        <div className={styles.car}>
          <div className={styles.car_title}>参与车辆</div>
          <div className={styles.car_list}>
            {
              projectCars.map((car, index)=>(
                index == expandCar ? 
                (<div key={car.equipCode} className={styles.car_item__expand}>
              <div className={styles.expand_title}>
                <div className={styles.expand_text}>{car.equipCode}</div>
                <div className={styles.expand_chart} onClick={()=>{ this.toCarDetail(car.equipCode) }}>图表</div>
              </div>
              <div className={styles.expand_inform}>
                <div className={styles.inform_row}>
                  <div className={styles.row_item}>泵送量：{car.quantityNum}方</div>
                  <div className={styles.row_item}>泵送计时：{(car.pumpDuration/3600).toFixed(2)}H</div>
                </div>
                <div className={styles.inform_row}>
                  <div className={styles.row_item}>总油耗：{car.oilNum}L</div>
                  <div className={styles.row_item}>方量油耗：{car.oilPerQuantity}L/方</div>
                </div>
                <div className={styles.up} onClick={()=>{ this.setState({ expandCar: 999 }) }}>
                  <img className={styles.up_icon} src={require('../assets/img/project/up.png')} />
                  收起
                </div>
              </div>
            </div>) : <div onClick={()=>{ this.setState({ expandCar: index }) }} key={car.equipCode} className={styles.car_item}>
              {car.equipCode}
            </div>
              ))
            }
          </div>
        </div>
        {/* 工程详情 */}
        <div className={styles.timeInform}>
            <div className={styles.inform_title}>工程详情</div>
            <div className={styles.inform_row}>开始时间：{projectTime.project ? projectTime.project.startTime : ''}</div>
            <div className={styles.inform_row}>{projectInfo.online==1?'最后进行时间':'结束时间'}：{projectTime.project ? projectTime.project.endTime : ''}</div>
            <div className={styles.inform_row}>工作车辆：{projectTime.bcNum}</div>
            {/* <div className={styles.inform_row}>工作车次：{projectTime.bcCount}</div> */}
            <div className={styles.inform_row}>转场次数：{projectTime.swithCount}</div>
        </div>
        <EditProjectModal refresh={this.init} ref={el=>{ this.editModal = el }} data={defaultData} />
      </div>
    )
  }
}
export default withRouter(ProjectDetail)